{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6321595e",
   "metadata": {},
   "source": [
    "# Cox生存分析\n",
    "\n",
    "* `mydir`：自己的数据\n",
    "* `ostime_column`: 数据对应的生存时间，不一定非的是OST，也可以是DST、FST等。\n",
    "* `os`：生存状态，不一定非的是OS，也可以是DS、FS等。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d604407f",
   "metadata": {},
   "outputs": [],
   "source": [
    "from lifelines import CoxPHFitter\n",
    "import pandas as pd\n",
    "from onekey_algo.custom.components.comp1 import normalize_df\n",
    "from sklearn.model_selection import train_test_split\n",
    "from onekey_algo import get_param_in_cwd\n",
    "from onekey_algo.custom.components.comp1 import fillna\n",
    "\n",
    "def get_prediction(mn):\n",
    "    subsets = get_param_in_cwd('subsets')\n",
    "    prediction = pd.concat([pd.read_csv(f'results/{mn}_cox_predictions_{subset}.csv') for subset in subsets],\n",
    "                           axis=0)\n",
    "    prediction.columns = ['ID', f'{mn}_Exp', mn]\n",
    "    return prediction[['ID', f'{mn}']]\n",
    "\n",
    "data = None\n",
    "for mn in get_param_in_cwd('summary_models'):\n",
    "    pred = get_prediction(mn)\n",
    "    pred['ID'] = pred['ID'].astype(str)\n",
    "    if data is None:\n",
    "        data = pred\n",
    "    else:\n",
    "        data = pd.merge(data, pred, on='ID', how='left')\n",
    "label_data = pd.read_csv(get_param_in_cwd('label_file'))\n",
    "label_data['ID'] = label_data['ID'].map(lambda x: f\"{x}.nii.gz\" if not (f\"{x}\".endswith('.nii.gz') or  f\"{x}\".endswith('.nii')) else x)\n",
    "data = pd.merge(data, label_data, on='ID', how='inner').drop_duplicates('ID').dropna(axis=0)\n",
    "\n",
    "data.to_csv('results/joinit_info.csv', index=False)\n",
    "data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "669023fa",
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "from lifelines import CoxPHFitter\n",
    "from lifelines.statistics import logrank_test\n",
    "from lifelines import KaplanMeierFitter\n",
    "from lifelines.plotting import add_at_risk_counts\n",
    "from lifelines.utils import concordance_index\n",
    "import numpy as np\n",
    "from onekey_algo.custom.components.metrics import calc_value_95ci\n",
    "\n",
    "def get_ci(a, sample_num):\n",
    "    l, h = calc_value_95ci(a, sample_num=sample_num)\n",
    "    return f\"{a:.3f}({l:.3f}-{h:.3f})\"\n",
    "\n",
    "metrics = []\n",
    "for mn in get_param_in_cwd('summary_models'):\n",
    "    task = mn.split('-')[-1]\n",
    "    metric = []\n",
    "    for subset in get_param_in_cwd('subsets'):\n",
    "        subdata = data[data['group'] == subset]#.dropna(axis=1)\n",
    "#         display(subdata)\n",
    "        cindex = concordance_index(subdata[get_param_in_cwd('duration_col')], subdata[mn], subdata[get_param_in_cwd('event_col')])\n",
    "        metric.append(get_ci(cindex, sample_num=subdata.shape[0]))\n",
    "    metrics.append(metric)\n",
    "metrics = pd.DataFrame(np.array(metrics).T, columns=get_param_in_cwd('summary_models'))\n",
    "metrics['Cohort'] = get_param_in_cwd('subsets')\n",
    "metrics.to_csv('results/metrics.csv', index=False)\n",
    "metrics"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5cf7e607",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
